import HttpUtils from '../HttpUtils/HttpUtils';
// 获取当前时间戳
// 获取当前时间戳
var timestamp = Date.parse(new Date()) / 1000;
Page({
	...HttpUtils.func,
	data: {
		contentShow: "contentShow",
		shareShow: "shareHide",
		allGatherShow: "allGatherHide",
		descriptionShow: "descriptionHide",
		colletIcon: "../../img/collectICON.png",
		collectStatus: "no",
		subId: '',
		subName: '',
		playImg: "../../img/movieICON.png",
		playUrl: "",

		on: "01",
		new: " new",
		pre: " pre",
		folderCode: 0,
		code: 0,
		content: {
			"keywords": '',
			"director": '',
			"actors": '',
			"originalCountry": '',
			"producedYear": '',
			"refCode": '',
			"publishTime": '',
			"name": '',
			"url": '',
			"duration": '',
			"type": '',
			"description": '',
			"subContentList": '',
			"subContentListAll": '',
			"updateItems": '',
			"sourceFrom": '',
		},
		name: '',
	},
	share(event) {     //点击分享
		this.setData({
			contentShow: "contentHide",
			shareShow: "shareShow"
		})
	},
	cancel(event) {      //取消分享
		this.setData({
			contentShow: "contentShow",
			shareShow: "shareHide",
		})
	},
	collection(event) {    //收藏
		var collectIcon = "../../img/collectFillICON.png";
		var collectStatus = event.target.dataset.status;
		if (collectStatus == "yes") {
			collectIcon = "../../img/collectICON.png";
			collectStatus = "no";
		} else {
			collectStatus = "yes";
		}
		this.setData({
			colletIcon: collectIcon,
			collectStatus: collectStatus

		})
	},
	descDetail(event) {  //显示简介
		this.setData({
			descriptionShow: "descriptionShow",
			contentShow: "contentHide"
		})
	},
	decriptionHide(event) {
		this.setData({
			descriptionShow: "descriptionHide",
			contentShow: "contentShow"
		})
	},
	allGather(event) {   //显示全部集数
		this.setData({
			contentShow: "contentHide",
			shareShow: "shareHide",
			allGatherShow: "allGatherShow",
		})
	},
	hideAllGather(event) {
		this.setData({
			contentShow: "contentShow",
			shareShow: "shareHide",
			allGatherShow: "allGatherHide",
		})
	},

	choose(e) {  //选择集数
    /*
    console.log(event.target.id);
    this.setData({
      on: event.target.id
    })
    */
		var subContentId = e.currentTarget.dataset.code;
		var epiNum = e.currentTarget.dataset.epinum;
		epiNum = parseInt(epiNum) + 1;
		this.setData({
			epiNum: epiNum
		});
		this.loadPlayUrl(subContentId);

	},
	goDetailPage(event) {
		wx.navigateTo({
			url: '../tvDetail/tvDetail?assetType=tv'
		})
	},
	onLoad(params) {
		wx.getSystemInfo({
			success: (res) => {   //播放器宽度设置
				this.setData({
					screenWidth: res.windowWidth,
					screenHeight: res.screenHeight
				})
			}
		});
		var playTaskId = this.formatDate("yyyyMMwx");
		var random = Math.round(Math.random() * 99999999999) + 100000000000;
		playTaskId += random;
		var folderCode = params.folderCode;
		var code = params.code;
		this.setData({
			code: code,
			folderCode: folderCode,
			playTaskId: playTaskId,
			"name": params.name,
			"subName": params.name,
			"timeNow": new Date().getTime()
		});
		//查询电视剧详情
		this.loawxetail();
		//是否收藏
		this.loadFavor();
		//热门推荐
		this.recommendList();

	},
	loawxetail: function(e) {
		//调用内容详情接口,获取内容详情
		var newUrl = getApp().globalData.dangjianUrl + "/content/contentQuery";
		var params = {};
		params["code"] = this.data.code + "";
		params["siteCode"] = getApp().globalData.siteCode + "";
		params["contentName"] = this.data.name + "";
		params["subCode"] = "";
		params = JSON.stringify(params);
		this.httpGet(newUrl, params, "电视剧详情加载失败").then(
			(respData) => {
				var result = respData.data.result.code;
				var subContentList = [];
				if (1 == result) {
					var content = respData.data.content;
					var thumbnail = content.thumbnail;
					if (null == thumbnail || "" == thumbnail) {
						var imageFiles = content.imageFiles;
						for (var j in imageFiles) {
							thumbnail = imageFiles[j].url;
							break;
						}
					}
					var contentItems = content.contentItems;
					var subContentListAll = [];
					if (null != contentItems && undefined != contentItems) {
						for (var index in contentItems) {
							var items = contentItems[index];
							if (index < 6) {
								//首页只显示6集电视剧子集
								items.index = "0" + (parseInt(index) + 1);
								subContentList.push(items);
								subContentListAll.push(items);
							} else {
								if (index < 9) {
									items.index = "0" + (parseInt(index) + 1);
								}
								subContentListAll.push(items);
							}
						}
					}
					this.setData({
						"content.keywords": content.keywords,
						"content.director": content.director,
						"content.actors": content.actors,
						"content.originalCountry": content.originalCountry,
						"content.producedYear": content.producedYear,
						"content.refCode": content.refCode,
						"content.publishTime": content.publishTime,
						"content.name": content.name,
						"content.url": thumbnail,
						"content.duration": content.duration,
						"content.type": content.type,
						"content.description": content.description,
						"content.subContentList": subContentList,
						"content.subContentListAll": subContentListAll,
						"content.updateItems": content.updateItems,
						"content.fromNa": null == content.fromNa || "" == content.fromNa ? "华数" : content.fromNa
					});
					//对于电视剧的播放需要查询调用一下内容播放查询接口定位到上一次播放到哪一集,自动从上次播放的集数开始播放awx by dingyf 20190509
					this.queryContentRecord();
        } else {
          this.showPageMsg("alert", respData.data.result.description) 
				}
			}
		);
	},
	//查询电视剧上次播放的集数
	queryContentRecord: function() {
		var episodeNum = 1;
		var newUrl = getApp().globalData.dangjianUrl + "/member/userPlayRecord";
		var params = {};
		params["code"] = this.data.code + "";
		params["contentType"] = "";
		params["subCode"] = "";
		params["taskId"] = "0";
		params = JSON.stringify(params);

		this.httpGet(newUrl, params, "查询电视剧上次播放集数失败").then(
			(respData) => {
				var result = respData.data.result.code;
				if (1 == result) {
					var record = respData.data.play;
					episodeNum = record.episodeNum;
					episodeNum = episodeNum <= 1 ? 1 : episodeNum;
					var subContentList = [];
					this.setData({
						epiNum: episodeNum
					});
					if (episodeNum > 7) {
						subContentList = this.data.content.subContentListAll;
						//首页的集数显示需要将当前播放的集数显示出来
						var start = 0;
						var end = 0;
						if (episodeNum < subContentList.length - 3) {
							start = episodeNum - 3;
							end = episodeNum + 3;
						} else {
							start = episodeNum - 6;
							end = episodeNum;
						}
						this.setData({
							"content.subContentList": subContentList.slice(start, end)
						});
					} else {
						subContentList = this.data.content.subContentList;
					}
					var subContentId = "";
					for (var index in subContentList) {
						var content = subContentList[index];
						if (episodeNum == parseInt(content.index)) {
							subContentId = content.itemCode;
							this.setData({
								"subId": content.itemCode,
								"subName": content.itemName,
							});
							break;
						}
					}
					//调用播放地址查询接口获取视频播放地址
					this.loadPlayUrl(subContentId);
        } else {
          this.showPageMsg("alert", respData.data.result.description) 
				}
			}
		);
		return episodeNum;
	},
	loadPlayUrl: function(subContentId) {
		//获取电视剧子集的播放地址
		var newUrl = getApp().globalData.dangjianUrl + "/content/contentUrlQuery";
		var params = {};
		params["code"] = subContentId + "";
		params["siteCode"] = getApp().globalData.siteCode + "";
		params["contentType"] = "1";    //1 公共内容 2本地内容
		params["from"] = "3";
		params = JSON.stringify(params);
		this.httpGet(newUrl, params, "视频地址查询失败").then(
			(respData) => {
				var result = respData.data.result.code;
				if (1 == result) {
					var playUrls = respData.data.content.playUrls;
					//设置集数选中效果
					var subContentList = this.data.content.subContentList;
					var newSubList = [];
					var newSubListAll = [];
					for (var index in subContentList) {
						var record = subContentList[index];
						if (subContentId == record.itemCode) {
							record.className = "on";
						} else {
							record.className = "";
						}
						newSubList.push(record);
					}
					var subContentListAll = this.data.content.subContentListAll;
					for (var index in subContentListAll) {
						var record = subContentListAll[index];
						if (subContentId == record.itemCode) {
							record.className = "on";
						} else {
							record.className = "";
						}
						newSubListAll.push(record);
					}
					this.setData({
						"content.playUrl": playUrls[0].url,
						"content.itemCode": playUrls[0].subCode,
						"content.subContentList": newSubList,
						//当前播放的子集ID
						"currentSubContentId": subContentId,
						"content.subContentListAll": newSubListAll
					});
        } else {
          this.showPageMsg("alert", respData.data.result.description) 
				}
			}
		);
	},
	//电视剧的收藏只记录到电视剧壳的收藏,点击任何子集都是收藏壳
	loadFavor: function(e) {
		var code = this.data.code;
		//获取是否已经收藏
		var newUrl = getApp().globalData.dangjianUrl + "/member/userContentIsFavor";
		// var params = '"code":"' + code + '","userId":"' + getApp().globalData.userId + '","corpId":"' + getApp().globalData.corpId + '",'
		// 	+ '"sign":"appKey=1&code=' + this.data.parentId + '&nonce=' + timestamp + '&siteCode=' + getApp().globalData.siteCode + '&timestamp=' + timestamp + '&appSecret=' + getApp().globalData.appSecret + '"}';
		var params = {};
		params["code"] = code + "";
		params["name"] = this.data.name + "";
		params = JSON.stringify(params);
		// var params="{'message': {'version': '1.0','header': {'action': 'REQUEST','command': 'USER_CONTENT_ISFAVOR','sequence': '10000000001'},'body': {'favor': {'userId': "+getApp().globalData.userId+",'contentType':1,'code': '"+code+"'}}}}";
		this.httpGet(newUrl, params, "是否收藏接口调用失败").then(
			(respData) => {
				var result = respData.data.result.code;
				if (1 == result) {
					var isFavor = respData.data.favor.isFavor;
					//默认为收藏的状态
					var favorIcon = "../../img/collectFillICON.png";
					if (isFavor == "false") {
						favorIcon = "../../img/collectICON.png";
					}
					this.setData({
						"content.favorIcon": favorIcon,
						"content.isFavor": isFavor
					});
        } else {
          this.showPageMsg("alert", respData.data.result.description) 
				}
			}
		);
	},
	favorContent: function(e) {
		//收藏内容
		var status = e.currentTarget.dataset.status;
		var contentName = e.currentTarget.dataset.name;
		status = "false" == status ? 1 : 0;
		var code = this.data.code;
		var newUrl = getApp().globalData.dangjianUrl + "/member/userContentFavor";
		var params = {};
		params["code"] = this.data.code + "";
		params["siteCode"] = getApp().globalData.siteCode + "";
		params["status"] = status + "";
		params["contentName"] = contentName + "";
		params["contentType"] = "1";
		params["columnCode"] = "";
		params = JSON.stringify(params);
		this.httpGet(newUrl, params, "内容收藏操作失败").then(
			(respData) => {
				var result = respData.data.result.code;
				var isFavor = "true";
				var favorIcon = "../../img/collectFillICON.png";
				if (1 == result) {
					if (0 == status) {
						favorIcon = "../../img/collectICON.png";
						isFavor = "false";
						this.showPageMsg("tips", "该内容收藏取消成功！");
					} else {
						this.showPageMsg("tips", "该内容收藏成功！");
					}
					this.setData({
						"content.favorIcon": favorIcon,
						"content.isFavor": isFavor
					});
        } else {
          this.showPageMsg("alert", respData.data.result.description) 
				}
			}
		);
	},
	recommendList: function(e) {
		var folderCode = this.data.folderCode;
		var refCode = this.data.content.refCode;
		if (null != refCode && undefined != refCode && "" != refCode) {
			folderCode = refCode;
		}
		var newUrl = getApp().globalData.dangjianUrl + "/content/relativeContentQuery";
		var params = {};
		params["pageIndex"] = "1";
		params["pageItems"] = "10";
		params["code"] = folderCode + "";
		params["siteCode"] = getApp().globalData.siteCode + "";
		params = JSON.stringify(params);
		// var params="{'message': {'version': '1.0','header': {'action': 'REQUEST','command': 'RELATIVE_CONTENT_QUERY','sequence': '10000000001'},'body': {'folder': {'code': "+folderCode+",'siteCode': "+getApp().globalData.siteCode+",'pageIndex': 1,'pageItems':10}}}}";
		this.httpGet(newUrl, params, "栏目下内容加载失败").then(
			(respData) => {
				var result = respData.data.result.code;
				if (1 == result) {
					var contents = respData.data.contents.content;
					var contentList = [];
					for (var index in contents) {
						var content = contents[index];
						//去掉自己本身一条数据
						if (this.data.code != content.code) {
							var json = {};
							var thumbnail = content.thumbnail;
							if (null == thumbnail || "" == thumbnail) {
								var imageFiles = content.imageFiles;
								for (var j in imageFiles) {
									if (imageFiles[j].type == getApp().globalData.imageType) {
										thumbnail = imageFiles[j].url;
										break;
									}
								}
							}
							json["name"] = content.name;
							json["publishTime"] = content.publishTime;
							json["url"] = thumbnail;
							json["code"] = content.code;
							json["type"] = content.type;
							json["foldCodes"] = folderCode;
							json["count"] = content.count;
							json["fromNa"] = '' == content.fromNa ? "华数" : content.fromNa; json["folderCode"] = folderCode;
							contentList.push(json);
						}
					}
					this.setData({
						"recommendList": contentList
					});
        } else {
          this.showPageMsg("alert", respData.data.result.description) 
				}
			}
		);
	},
	bindListnerPlay: function(e) {
		//视频播放记录上传(整数分钟上传)
		var timePoints = e.detail.currentTime;
		timePoints = Math.ceil(timePoints);
		var time = new Date().getTime();
		var lastPlayTime = this.data.timeNow;
		var different = time - lastPlayTime;
		timePoints = Math.ceil(timePoints);
		this.setData({
			"currentTimePoints": timePoints
		});
		var lastTimePoints = this.data.lastTimePoints;
		if (timePoints > 0 && different > 60 * 1000) {
			//需要上传播放记录,同时将当前的时间点设置到timePoints
			if (timePoints != lastTimePoints) {
				this.setData({
					"lastTimePoints": timePoints,
					"timeNow": time
				});
				//只要上传就传60s,误差忽略
				this.uploadPlayRecord(timePoints);
			}
		}
	},
	onPlayOver: function(e) {
		//视频播放结束上传
		this.uploadPlayRecord(this.data.content.duration);
	},
	onUnload: function(e) {
		//页面被关闭时调用一次
		var currentTimePoints = this.data.currentTimePoints;
		if (currentTimePoints > 0) {
			//此处进度条时间不一定是整数分钟,按照实际的显示,播放时长还是按照60s计算
			this.uploadPlayRecord(currentTimePoints);
		}
	},
	uploadPlayRecord: function(timePoints) {
		var now = this.formatDate("yyyy-MM-wx hh:mm:ss", new Date());
		var newUrl = getApp().globalData.dangjianUrl + "/member/userPlayDuration";

		var params = {};
		params["code"] = this.data.code + "";
		params["subCode"] = this.data.subId + "";
		params["subName"] = this.data.subName + "";
		params["taskId"] = "0";
		params["duration"] = 60;
		params["playTaskId"] = this.data.playTaskId + "";
		params["playtime"] = now + "";
		params["contentType"] = 1;
		params["durationTotal"] = this.data.content.duration + "";
		params["from"] = 1;
		params["type"] = this.data.content.type;
		params["episodeNum"] = "" + this.data.epiNum;
		params["timePoints"] = Math.ceil(timePoints / 1000) + "";
		params["name"] = this.data.content.name + "";
		params = JSON.stringify(params);

		// var params = '{"timestamp":"' + timestamp + '","nonce":"' + timestamp +
		//  '","appKey":"1","corpId":"' + getApp().globalData.corpId + '","userId":"'  + getApp().globalData.userId + 
		//  '","code":"' + this.data.code + '","subCode":"' + this.data.currentSubContentId +
		//   '","subName":"' + this.data.subName + '","taskId":"0","duration":"' +60 + 
		// 	'","playTaskId":"123abc","playtime":"' + now + 
		// 	'","contentType":"1","durationTotal":"' + this.data.content.duration + 
		// 	'","from":"1","type":"' + this.data.content.type + 
		// 	'","episodeNum":"' + this.data.epiNum + '","timePoints":"' + timePoints + 
		// 	'","name":"' + this.data.content.name + '",'
		// + '"sign":"appKey=1&code=' + this.data.parentId + '&nonce=' + timestamp + '&siteCode=' + getApp().globalData.siteCode + '&timestamp=' + timestamp + '&appSecret=' + getApp().globalData.appSecret + '"}';

		// var params = "{'message': {'body': {'play': {'code': '" + this.data.code + "','columnCode': " + this.data.folderCode + ",'contentName':'" + this.data.content.name + "','contentType': '1','duration': 60,'subCode':'" + this.data.currentSubContentId + "','durationTotal': " + this.data.content.duration + ",'from': '1','itemCode': '" + this.data.content.itemCode + "','episodeNum':" + this.data.epiNum + ",'playTaskId': '" + this.data.playTaskId + "','playtime': '" + now + "','taskId':'','timePoints': " + timePoints + ",'type': '" + this.data.content.type + "','userId': " + getApp().globalData.userId + "}},'header': {'action': 'REQUEST','command': 'USER_PLAY_DUATION','sequence': '10000000001'},'version': '1.0'}}";
		this.httpGet(newUrl, params, "上传播放记录异常").then(
			(respData) => {
				var result = respData.data.result.code;
				if (1 == result) {
					console.log("上传播放记录成功");
        } else {
          this.showPageMsg("alert", respData.data.result.description) 
				}
			}
		);
	},
	articleDetail(e) {
		var folderCode = e.currentTarget.dataset.foldercode;
		var type = e.currentTarget.dataset.type;
		var code = e.currentTarget.dataset.code;
		var name = e.currentTarget.dataset.name;
		var detailUrl = this.getUrl(type, code, folderCode, name);
		console.log("跳转地址：" + detailUrl);
		if (detailUrl.length > 0) {
			wx.navigateTo({
				url: detailUrl
			});
		} else {
      this.showPageMsg("tips","该内容类型详情页暂未开发")  
		}
	}
});
